package com.lianqi.emcpframework.commons.bean.validate;

import com.lianqi.emcpframework.core.bean.SimpleValidateResults;
import com.lianqi.emcpframework.core.bean.ValidationException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;

/**
 * @program emcp-framework
 * @ClassName BeanValidator
 * @description: bean校验工具类
 * @author: sky
 * @create: 2018/11/21 15:46
 */
public class BeanValidator {

    static volatile Validator validator;

    public static Validator getValidator(){
        if (validator == null){
            synchronized (BeanValidator.class){
                ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
                return validator = factory.getValidator();
            }
        }
        return validator;
    }

    public static <T> T tryValidate(T bean,Class... group){
        Set<ConstraintViolation<T>> violations = getValidator().validate(bean,group);
        if (!violations.isEmpty()) {
            SimpleValidateResults results = new SimpleValidateResults();
            for (ConstraintViolation<T> violation : violations) {
                results.addResult(violation.getPropertyPath().toString(), violation.getMessage());
            }
            throw new ValidationException(results);
        }
        return bean;
    }
}
